//
//  GGTTeamBuyViewController.m
//  GGT
//
//  Created by 安静的美男子 on 14/10/27.
//  Copyright (c) 2014年 GGT. All rights reserved.
//

#import "GGTTeamBuyViewController.h"
#import "DPRequest.h"
#import "GGTAppDelegate.h"
#import "GGTCityListViewController.h"
#import "GGTTeamBuyTableViewCell.h"
#import "GGTTeamBuyModel.h"
#import "GGTTeamBuyDetailViewController.h"
#import "GGTMoreKindViewController.h"
#import "AutoScrollView.h"
#import "MBProgressHUD.h"
#import "GGTButtonViewController.h"
@interface GGTTeamBuyViewController ()<DPRequestDelegate,UITableViewDelegate, UITableViewDataSource,UIScrollViewDelegate>
@property (nonatomic, assign) int flag;//标志位

@property (nonatomic, retain) NSMutableDictionary *teamBuyIDDic; //解析后的字典result

@property (nonatomic, retain) NSMutableDictionary *teamBuyDIC;//解析后的字典result

@property (nonatomic, retain) NSMutableArray *teamBuyArray;//团购数组
@property (nonatomic, retain) NSString *teamBuyIDs;//团购ID
@property (nonatomic, retain) UITableView *teamBuyTableView;//新增团购tableView
@property (nonatomic, retain) UIScrollView *scrollView;
@property (nonatomic, retain) UIScrollView *bannerScrollView;
@property (nonatomic, retain) GGTTeamBuyModel *teamBuy;
//MBProgressHUD
@property (nonatomic, retain) MBProgressHUD *hud;
//主页面button tag值
@property (nonatomic, assign) int targe;

@end

@implementation GGTTeamBuyViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //数据初始化
        self.teamBuyArray = [NSMutableArray array];
        self.teamBuyIDDic = [NSMutableDictionary dictionary];
        self.teamBuyDIC = [NSMutableDictionary dictionary];
        self.flag = 0;
        
        //判断是否为第一次运行程序
        NSUserDefaults *accoutDefaults = [NSUserDefaults standardUserDefaults];
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"isFirst"] == nil) {
            //设定默认城市
            NSString *cityName = @"大连";
            [accoutDefaults setObject:cityName forKey:@"cityName"];
            //设定默认地图类型
            NSString *mapType = @"0";
            [accoutDefaults setObject:mapType forKey:@"mapType"];
            
            [[NSUserDefaults standardUserDefaults] setObject:@"yes" forKey:@"isFirst"];
        } else {
            
        }
        [accoutDefaults synchronize];
        
        //注册通知中心
        NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
        [notiCenter addObserver:self selector:@selector(receiveNotification:) name:@"cesuo" object:nil];
    }
    return self;
}
//收到通知后执行
- (void)receiveNotification:(NSNotification *)noti
{
    
    [self.teamBuyArray removeAllObjects];
    [self.teamBuyIDDic removeAllObjects];
    [self.teamBuyDIC removeAllObjects];
    
    
    NSUserDefaults *accoutDefaults = [NSUserDefaults standardUserDefaults];
    //设定leftBarButtonItemTitle
    [self.navigationItem.leftBarButtonItem setTitle:[accoutDefaults objectForKey:@"cityName"]];
    
    //获取团购ID
    [[GGTAppDelegate instance] setAppKey:@"1302010222"];
    [[GGTAppDelegate instance] setAppSecret:@"48bfe6dbfa55422e8276eca9d05cefd7"];
    NSString *url = @"v1/deal/get_daily_new_id_list";
    NSString *params = [NSString stringWithFormat:@"city=%@&date=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"cityName"], [self getTodayDate]];
    [[[GGTAppDelegate instance] dpapi] requestWithURL:url paramsString:params delegate:self];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //
    NSUserDefaults *accoutDefaults = [NSUserDefaults standardUserDefaults];
    NSString *cityName = [accoutDefaults objectForKey:@"cityName"];
    
    
    
    //获取团购ID
    [[GGTAppDelegate instance] setAppKey:@"1302010222"];
    [[GGTAppDelegate instance] setAppSecret:@"48bfe6dbfa55422e8276eca9d05cefd7"];
    NSString *url = @"v1/deal/get_daily_new_id_list";
    NSString *params = [NSString stringWithFormat:@"city=%@&date=%@",cityName, [self getTodayDate]];
    [[[GGTAppDelegate instance] dpapi] requestWithURL:url paramsString:params delegate:self];
    
    //选择城市按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:[NSString stringWithFormat:@"%@",cityName] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonClicked:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"liebiao.png"] style:UIBarButtonItemStylePlain target:self action:@selector(buttonClicked:)];
    self.navigationItem.rightBarButtonItem.tintColor =  [UIColor blackColor];
    //scrollView
    self.scrollView = [[UIScrollView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    self.scrollView.delegate = self;
    [self.view addSubview:self.scrollView];
    //banner
    //首页轮播广告
    AutoScrollView *myBarnner = [[AutoScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 150) imageNames:@[@"夜晚.png",@"旅游.png",@"美食.png",@"购物.png",@"酒店.png",]];
    myBarnner.showPageControl = YES;
    myBarnner.timeInterval= 3;
    
    [self.scrollView addSubview:myBarnner];
    //button
    NSArray *array = [NSArray arrayWithObjects:@"0.png", @"3.png", @"4.png", @"5.png", nil];
    NSArray *titleArr = [NSArray arrayWithObjects:@"休闲娱乐", @"强身健体", @"购物达人", @"完美主妇", nil];
    //首页button
    self.targe = 5000;
    for (int i = 0; i < 4; i++) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake( 13 + i * 75, 160, 70, 90)];
        [self.scrollView addSubview:view];
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 70, 60)];
        imgView.image = [UIImage imageNamed:array[i]];
        [view addSubview:imgView];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 60, 70, 40)];
        label.text = titleArr[i];
        [view addSubview:label];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        //button.backgroundColor = [UIColor redColor];
        button.frame = CGRectMake(0, 0, 70, 90);
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
        [button setTag:self.targe];
        [imgView release];
        [label release];
        [view release];
        self.targe++;
    }
    
    //今日新增tableView
    self.teamBuyTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 260, 320, 480) style:UITableViewStyleGrouped];
    self.teamBuyTableView.rowHeight = 120;
    self.teamBuyTableView.scrollEnabled = NO;
    self.teamBuyTableView.dataSource = self;
    self.teamBuyTableView.delegate = self;
    [self.scrollView addSubview:self.teamBuyTableView];
    [self.teamBuyTableView release];
    
    //HUB
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"获取今日团购";
    [self.hud setMode:MBProgressHUDModeIndeterminate];
}
//特色分类点击调用
- (void)buttonClick:(UIButton *)button
{
    
    if (button.tag == 5000) {
        //点击button调用方法 将str 值传到下一个页面
        [self pushMyControllerStr1:@"医院" Str2:@"旅游" Str3:@"汽车服务"];
    } else if (button.tag == 5001) {
        [self pushMyControllerStr1:@"健身中心" Str2:@"舞蹈" Str3:@"体检中心"];
    } else if (button.tag == 5002) {
        [self pushMyControllerStr1:@"花店" Str2:@"服饰鞋包" Str3:@"家居建材"];
    } else if (button.tag == 5003) {
        [self pushMyControllerStr1:@"瑜伽" Str2:@"瘦身纤体" Str3:@"洗衣店"];
    }
}
//跳转特色分类服务页面函数
- (void)pushMyControllerStr1:(NSString *)str1
                        Str2:(NSString *)str2
                        Str3:(NSString *)str3
{
    //推出下个界面
    GGTButtonViewController *buttonVC =[[GGTButtonViewController alloc]init];
    buttonVC.str1 = str1;
    buttonVC.str2 = str2;
    buttonVC.str3 = str3;
    [self.navigationController pushViewController:buttonVC animated:YES];
}


//判断是否隐藏navigationBar
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //    if (scrollView.contentOffset.y > 10) {
    //        self.navigationController.navigationBarHidden = YES;
    //    } else {
    //        self.navigationController.navigationBarHidden = NO;
    //    }
    
}
//获取当前日期
- (NSString *)getTodayDate
{
    
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd"];
    NSString * dateStr=[dateformatter stringFromDate:localeDate];
    return dateStr;
}
//更多分类点击调用

- (void)buttonClicked:(UIBarButtonItem *)button
{
    // 推出分类界面
    GGTMoreKindViewController *moreKindVC = [[GGTMoreKindViewController alloc]init];
    [self.navigationController pushViewController:moreKindVC animated:YES];
    [moreKindVC release];
    
}
//选择城市按钮

- (void)leftBarButtonClicked:(UIBarButtonItem *)button
{
    GGTCityListViewController *cityListVC = [[GGTCityListViewController alloc]init];
    UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:cityListVC];
    [navVC setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    [self presentViewController:navVC animated:YES completion:^{
        //推出新视图之后,要执行的代码
    }];
}

#pragma mark - 豆瓣相关回调函数

- (void)request:(DPRequest *)request didFailWithError:(NSError *)error
{
    //self.resultTextView.contentOffset = CGPointZero;
    NSLog(@"注意参数或地址填写错误:%@",[error description]);
    
}

- (void)request:(DPRequest *)request didFinishLoadingWithResult:(id)result
{
    //self.resultTextView.contentOffset = CGPointZero;
    // NSLog(@"%@", request.getURL);
    if (self.flag % 2 == 0) {
        
        self.teamBuyIDDic = result;
        
        NSArray *IDArr = [self.teamBuyIDDic objectForKey:@"id_list"];
        
        if (IDArr.count == 0) {
            
        } else{
            NSMutableString *str1 = [[NSMutableString alloc]init];
            if (IDArr.count < 40) {
                for (NSString *s2 in IDArr) {
                    [str1 appendFormat:@"%@,", s2];
                }
            } else {
                for (int i = 0; i < 40; i++) {
                    [str1 appendFormat:@"%@,",[IDArr objectAtIndex:i]];
                }
            }
            
            
            self.teamBuyIDs = [str1 substringToIndex:[str1 length] - 1];
            //批量获取团购信息
            NSString *url2 = @"v1/deal/get_batch_deals_by_id";
            NSString *params2 = [NSString stringWithFormat:@"deal_ids=%@", self.teamBuyIDs];
            
            [[[GGTAppDelegate instance] dpapi] requestWithURL:url2 paramsString:params2 delegate:self];
        }
        
    } else {
        self.teamBuyDIC = result;
        NSMutableArray *teamBuyArr = [self.teamBuyDIC objectForKey:@"deals"];
        for (NSDictionary *dic in teamBuyArr) {
            GGTTeamBuyModel *GGTTeamBuy = [[GGTTeamBuyModel alloc]initWithDictionary:dic];
            [self.teamBuyArray addObject:GGTTeamBuy];
            
        }
        
    }
    self.flag++;
    [self.teamBuyTableView reloadData];
    [self.hud hide:YES];
    [self.hud removeFromSuperview];
    
}

//section头的内容
#pragma mark - tableView相关回调
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"今日新增团购";
}
//section的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
//每个section中有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //NSLog(@"%@", self.teamBuyArray);
    NSInteger i = self.teamBuyArray.count;
    tableView.frame = CGRectMake(0, 260, 320, 120 * i + 30);
    self.scrollView.contentSize = CGSizeMake(320, 260 + 120 * i + 30);
    
    return [self.teamBuyArray count];
}
//给cell赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GGTTeamBuyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewBuy"];
    if (cell == nil) {
        cell = [[[GGTTeamBuyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NewBuy"]autorelease];
    }
    GGTTeamBuyModel *GGTTeam = [self.teamBuyArray objectAtIndex:indexPath.row];
    cell.GGTTeamBuy = GGTTeam;
    return cell;
}
//cell 的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GGTTeamBuyDetailViewController *detail = [[GGTTeamBuyDetailViewController alloc]init];
    //将一个对象传给下一个页面
    detail.GGTTeamBuyDetail = [self.teamBuyArray objectAtIndex:indexPath.row];
    
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
    
}
- (void)dealloc
{
    //移除监听事件
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [_teamBuyDIC release];
    [_teamBuyIDDic release];
    [_teamBuyTableView release];
    [_teamBuyArray release];
    [_teamBuyIDs release];
    [_bannerScrollView release];
    [super dealloc];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
